package wiki.tools.vidition.droid.util;

import java.util.ArrayList;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import wiki.tools.vidition.droid.util.bean.NewsItem;
import android.text.TextUtils;

public class SeaxParssNews extends DefaultHandler {
	private ArrayList<NewsItem> rss;
	private Stack<String> stack;
	private StringBuilder builder;
	private NewsItem item;

	public SeaxParssNews() {
		stack = new Stack<String>();
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String temp = new String(ch, start, length);
		if (!TextUtils.isEmpty(temp)) {
			builder.append(temp);
		}
		super.characters(ch, start, length);
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		String node = stack.pop();
		if (stack.size() == 0) {
			return;
		}
		boolean isNewItem = stack.peek().equals("item") ? true : false;
		String value = builder.toString();
		if (node.equals("title") && isNewItem) {
			item.title = value;
		} else if (node.equals("description") && isNewItem) {
			Pattern pattern = Pattern.compile("<.*?>");
			Matcher matcher = pattern.matcher(value);
			String temp;
			while (matcher.find()) {
				temp = matcher.group();
				value = value.replace(temp, "");
			}
			item.description = value;
		} else if (isNewItem && node.equals("guid")) {
			item.link = value;
		} else if (node.equals("item")) {
			rss.add(item);
		}
		super.endElement(uri, localName, name);
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		if (localName.equals("channel")) {
			rss = new ArrayList<NewsItem>();
		} else if (localName.equals("item")) {
			item = new NewsItem();
		}
		stack.push(localName);
		builder = new StringBuilder();
		super.startElement(uri, localName, name, attributes);

	}

	public ArrayList<NewsItem> getRSS() {
		return rss;
	}
}